const express = require("express");
const pelletRouter = require("./routes/pellet");
const eventRouter = require("./routes/event");
const eraRouter = require("./routes/era");
const bodyParser = require("body-parser");

const app = express();
// 自动解析body
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.all("*", (req, res, next) => {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.setHeader("Access-Control-Allow-Origin", "*");
    //跨域允许的header类型
    res.setHeader(
        "Access-Control-Allow-Headers",
        "Content-type,Content-Length,Authorization,Accept,X-Requested-Width"
    );
    //跨域允许的请求方式
    res.setHeader(
        "Access-Control-Allow-Methods",
        "PUT,POST,GET,DELETE,OPTIONS"
    );
    next();
});
app.use("/pellet", pelletRouter);
app.use("/event", eventRouter);
app.use("/era", eraRouter);
// 捕获 404
app.use((req, res, next) => {
    res.send(404);
});
// 错误处理器
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    // 设置 locals，只在开发环境提供错误信息
    res.locals.message = err.message;
    res.locals.error = req.app.get("env") === "development" ? err : {};
    res.send(500);
});

app.listen("8989", () => {
    console.log("database opened");
});

module.exports = app;
